package com.dd.cloud.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * Ase加密 对敏感数据加解密
 *
 * @Author: czg
 * @Date: 2022-01-04 17:15:15
 */
public class AESUtil {
    /**
     * 加密秘钥
     */
    public static final String SECRET_KEY = "www.zekekeji.com";
    /**
     * 开放接口数据加密秘钥
     */
    public static final String OPEN_API_KEY = "1e236487107ce894ba9292087c520903";
    private static final String ENCODING = "UTF-8"; // 编码
    private static final String ALGORITHM = "AES"; //算法
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; // 默认的加密算法，ECB模式

    /**
     * 加密
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null || sKey.length() == 0) {
            System.out.print("Key为空null");
            return null;
        }
        if (sKey.length() % 16 != 0) {
            System.out.print("Key长度不是16的倍数");
            return null;
        }
        byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return new Base64().encodeToString(encrypted);
    }

    /**
     * 解密
     *
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            if (sKey == null || sKey.length() == 0) {
                System.out.print("Key为空null");
                return null;
            }
            if (sKey.length() % 16 != 0) {
                System.out.print("Key长度不是16的倍数");
                return null;
            }
            if (StringUtils.isBlank(sSrc)){
                return "";
            }
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //先用base64解密
            byte[] encrypted1 = new Base64().decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                return new String(original, StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String queryString = "0=c&1=K&2=z&3=h&4=b&5=m&6=V&7=3&8=z&9=7&10=w&11=j&12=1&13=U&14=d&15=7&16=B&17=Z&18=r&19=2&20=u&21=A&22==&23==";
        URL url = new URL("http://example.com?" + URLEncoder.encode(queryString, "UTF-8"));
        String query = queryString(queryString);
        System.out.println(query);
        String s = "yG977Xm1CuRP8DQXhDwVcQ==";
        //String s1 = jsonString(s);
        System.out.println("json转:" + s);
        String str1 = "account=13760801112&password=123456";
        String str = "{\"phone\":\"13760801112\",\"psw\":\"123456\",\"type\":1,\"platId\":\"\",\"appId\":\"\",\"model\":\"111111\",\"cid\":\"\"}";
        String key = "MTIzNDU3Nzp5MEFC";
        String encrypt = encrypt(str1, key);
        System.out.println(encrypt);
        String str2 = "+VJL8mDHHlFUP/TG16oKUsEuIO0VxiWIcHv+eWzwGJ0d/G/Xnmduzkr3CDH+3n2dOHopdnhk58QGwXfzQ2GDaSuxoo+QzPUUtfiiTsXpHSsqDQY6v6SxZAIYRWYxV2tvDDehYNPh9d8ZMQ20BdIMBbCyi2y2QuJjyYGUudU19hhR5YcQ1A4uf9arQ9BsEDwpjVzAxNKpeCSfeg1e4DrgfI5S9xu6WEABilBDr3WakWrTsB8g3Ctx2vlTaJavMrowa9vwsyGfkkc6InIXjb0gXkHMT3plawhUGvH794JEBd9268Q6VKwCi54LZyYiW0rk4x8om5ym5kae5iVDnm/LnuaGmQdIFkQf9jGztyWDci9Xt6y0DS4G0YuoMV6P8YvbVdQ3WcASLu5Fio9q46ffC5GRmQJWQPjHAxKQTL2jH2arE1OETIklEQFhLc7eIJIY+Svv0WuRHONqNM521+aBwFDpYeNnF0wBDm9ME3axydCL+UKqlWEkemPinJ3Y3f9C6iFpCB1nSH4X/kz1zVX4tGZh5AbNlwcHktakkVgHF6Nk8l2IIXTgdamHLV6do2V/Le0IgCufNOOuYJpJKkDpzQ";
        try {
            String params = AESUtil.decrypt(str2, key);
            System.out.println("解密后" + params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String queryString(String queryString){
        if (StringUtils.isBlank(queryString) || queryString.indexOf("&") < 0){
            return queryString;
        }
        String[] params = queryString.split("&");
        StringBuilder sb = new StringBuilder();
        for (String param : params) {
            String substring = param.substring(param.indexOf("=")+1);
            sb.append(substring);

//            String[] keyValue = param.split("=");
//            if (keyValue.length == 2) {
//                sb.append(keyValue[1]);
//            }
        }
        return sb.toString();
    }

    public static String jsonString(String jsonString){
        JSONObject jsonObject = JSONObject.parseObject(jsonString, Feature.OrderedField);
        System.out.println(jsonObject);
        Set<String> keys = jsonObject.keySet();
        StringBuilder sb = new StringBuilder();
        keys.forEach(item ->{
            String string = jsonObject.getString(item);
            sb.append(string);
        });
        return sb.toString();
    }
}